<template>
  <div class="article-management">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">文章管理</h1>
        <p class="page-desc">管理站点文章内容，支持多种文章类型和状态管理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="Plus" @click="handleAdd" class="add-btn">
          新建文章
        </el-button>
      </div>
    </div>

    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="站点">
          <el-select
            v-model="searchForm.siteId"
            placeholder="选择站点"
            clearable
            @change="handleSiteChange"
            style="width: 160px"
          >
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="栏目">
          <el-select
            v-model="searchForm.channelId"
            placeholder="选择栏目"
            clearable
            style="width: 160px"
          >
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="已发布" :value="0" />
            <el-option label="草稿" :value="1" />
            <el-option label="待审核" :value="2" />
            <el-option label="待发布" :value="5" />
            <el-option label="草稿" :value="10" />
          </el-select>
        </el-form-item>

        <el-form-item label="标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入文章标题"
            style="width: 220px"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <div class="table-info">
          <span class="total-count">共 {{ pagination.total }} 条记录</span>
        </div>
        <div class="table-actions">
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            :disabled="selectedIds.length === 0"
            @click="handleBatchDelete"
            plain
          >
            批量删除
          </el-button>
          <el-button
            type="success"
            size="small"
            icon="Check"
            :disabled="selectedIds.length === 0"
            @click="handleBatchPublish"
            plain
          >
            批量发布
          </el-button>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table
          :data="articleList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="标题" min-width="300">
            <template #default="{ row }">
              <div class="article-item">
                <div class="article-image-wrapper" v-if="row.image">
                  <img :src="row.image" class="article-image" />
                </div>
                <div class="article-content">
                  <div class="article-title" @click="handleEdit(row)">
                    {{ row.title }}
                  </div>
                  <div class="article-subtitle" v-if="row.subtitle">
                    {{ row.subtitle }}
                  </div>
                  <div class="article-meta">
                    <span class="meta-item">{{ row.author || '未知作者' }}</span>
                    <span class="meta-item">浏览 {{ row.views || 0 }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="channel.name"
            label="栏目"
            width="120"
            align="center"
          >
            <template #default="{ row }">
              <el-tag size="small" type="info">{{ row.channel?.name || '-' }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="publishDate"
            label="发布时间"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              <div class="date-text">
                {{ row.publishDate ? formatDate(row.publishDate) : '-' }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="createdAt"
            label="创建时间"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              <div class="date-text">
                {{ formatDate(row.createdAt) }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" text @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  text
                  @click="handlePreview(row)"
                  v-if="row.status === 0"
                >
                  预览
                </el-button>
                <el-dropdown
                  @command="(command) => handleCommand(command, row)"
                  trigger="click"
                >
                  <el-button type="info" size="small" text>
                    更多<el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        command="publish"
                        v-if="row.status !== 0"
                      >
                        发布
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="withdraw"
                        v-if="row.status === 0"
                      >
                        撤回
                      </el-dropdown-item>
                      <el-dropdown-item command="copy">
                        复制
                      </el-dropdown-item>
                      <el-dropdown-item command="debug">
                        调试信息
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { articleApi } from '@/api/article'
import type { Article, Channel, Site } from '@/types/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
// 修改为支持字符串ID，避免精度丢失
const selectedIds = ref<(number | string)[]>([])

// 站点和栏目数据
const sites = ref<Site[]>([])
const channels = ref<Channel[]>([])

// 搜索表单
const searchForm = reactive({
  siteId: undefined as number | undefined,
  channelId: undefined as number | undefined,
  status: undefined as number | undefined,
  title: '',
})

// 文章列表
const articleList = ref<Article[]>([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0,
})

// 获取站点列表
const getSites = async () => {
  try {
    // 调用站点树形结构API
    const response = await fetch('/cms/admin/site/tree', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    })
    const result = await response.json()

    if (result.code === 0) {
      sites.value = result.data || []
    }
  } catch (error) {
    console.error('获取站点列表失败:', error)
  }
}

// 获取栏目列表
const getChannels = async (siteId: number) => {
  try {
    // 根据站点ID获取栏目树形结构
    const response = await fetch(`/cms/admin/channel/tree?siteId=${siteId}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    })
    const result = await response.json()

    if (result.code === 0) {
      channels.value = result.data || []
    }
  } catch (error) {
    console.error('获取栏目列表失败:', error)
  }
}

// 获取文章列表
const getArticleList = async () => {
  try {
    loading.value = true

    // 过滤掉undefined和空值的参数
    const params: any = {
      current: pagination.current,
      size: pagination.size,
    }

    if (searchForm.siteId !== undefined && searchForm.siteId !== null) {
      params.siteId = searchForm.siteId
    }
    if (searchForm.channelId !== undefined && searchForm.channelId !== null) {
      params.channelId = searchForm.channelId
    }
    if (searchForm.status !== undefined && searchForm.status !== null) {
      params.status = searchForm.status
    }
    if (searchForm.title && searchForm.title.trim()) {
      params.title = searchForm.title.trim()
    }

    const response = await articleApi.getArticlePage(params)
    articleList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 处理站点变更
const handleSiteChange = (siteId: number) => {
  searchForm.channelId = undefined
  if (siteId) {
    getChannels(siteId)
  } else {
    channels.value = []
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  getArticleList()
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    siteId: undefined,
    channelId: undefined,
    status: undefined,
    title: '',
  })
  channels.value = []
  pagination.current = 1
  getArticleList()
}

// 处理新增
const handleAdd = () => {
  router.push('/content/article/edit')
}

// 处理编辑
const handleEdit = (row: Article) => {
  router.push(`/content/article/edit/${row.id}`)
}

// 处理预览
const handlePreview = (row: Article) => {
  // 构建正确的预览URL，直接访问后端portal接口
  const baseUrl = window.location.origin
  const previewUrl = `${baseUrl}/cms/portal/article/${row.id}`
  window.open(previewUrl, '_blank')
}

// 处理命令
const handleCommand = async (command: string, row: Article) => {
  switch (command) {
    case 'publish':
      await handlePublish(row)
      break
    case 'withdraw':
      await handleWithdraw(row)
      break
    case 'copy':
      await handleCopy(row)
      break
    case 'debug':
      await handleDebug(row)
      break
    case 'delete':
      await handleDelete(row)
      break
  }
}

// 处理发布
const handlePublish = async (row: Article) => {
  try {
    await articleApi.publishArticle(row.id)
    ElMessage.success('发布成功')
    getArticleList()
  } catch (error) {
    console.error('发布文章失败:', error)
  }
}

// 处理撤回
const handleWithdraw = async (row: Article) => {
  try {
    await articleApi.withdrawArticle(row.id)
    ElMessage.success('撤回成功')
    getArticleList()
  } catch (error) {
    console.error('撤回文章失败:', error)
  }
}

// 处理复制
const handleCopy = async (row: Article) => {
  // TODO: 实现文章复制功能
  ElMessage.info('复制功能待实现')
}

// 处理调试
const handleDebug = async (row: Article) => {
  try {
    const result = await articleApi.debugArticle(row.id)
    if (result.code === 0) {
      const debug = result.data
      const message = `
        文章ID: ${debug.id}
        标题: ${debug.title}
        状态: ${debug.status} (${debug.statusText})
        站点ID: ${debug.siteId}
        栏目ID: ${debug.channelId}
        发布时间: ${debug.publishDate || '未设置'}
        创建时间: ${debug.createdAt}
        更新时间: ${debug.updatedAt}
        前台可显示: ${debug.canShow ? '是' : '否'}
      `.trim()

      ElMessageBox.alert(message, '文章调试信息', {
        confirmButtonText: '确定',
        type: 'info',
      })
    } else {
      ElMessage.error(result.msg || '获取调试信息失败')
    }
  } catch (error) {
    console.error('获取调试信息失败:', error)
    ElMessage.error('获取调试信息失败')
  }
}

// 处理删除
const handleDelete = async (row: Article) => {
  ElMessageBox.confirm(`确定要删除文章"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await articleApi.deleteArticle(row.id)
      ElMessage.success('删除成功')
      getArticleList()
    } catch (error) {
      console.error('删除文章失败:', error)
    }
  })
}

// 处理选择变更
const handleSelectionChange = (selection: Article[]) => {
  selectedIds.value = selection.map((item) => item.id)
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的文章')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 篇文章吗？此操作不可恢复！`,
    '批量删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
  ).then(async () => {
    try {
      console.log('开始批量删除文章，IDs:', selectedIds.value)

      const response = await articleApi.batchDeleteArticles(selectedIds.value)
      console.log('批量删除响应:', response)

      if (response.code === 0) {
        ElMessage.success(`批量删除成功，共删除 ${selectedIds.value.length} 篇文章`)
        selectedIds.value = [] // 清空选择
        getArticleList() // 刷新列表
      } else {
        ElMessage.error(response.msg || '批量删除失败')
      }
    } catch (error: any) {
      console.error('批量删除失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '批量删除失败，请重试')
    }
  }).catch(() => {
    // 用户取消删除
    console.log('用户取消批量删除')
  })
}

// 处理批量发布
const handleBatchPublish = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要发布的文章')
    return
  }

  ElMessageBox.confirm(
    `确定要发布选中的 ${selectedIds.value.length} 篇文章吗？`,
    '批量发布确认',
    {
      confirmButtonText: '确定发布',
      cancelButtonText: '取消',
      type: 'info',
    }
  ).then(async () => {
    try {
      console.log('开始批量发布文章，IDs:', selectedIds.value)

      const response = await articleApi.batchPublishArticles(selectedIds.value)
      console.log('批量发布响应:', response)

      if (response.code === 0) {
        ElMessage.success(`批量发布成功，共发布 ${selectedIds.value.length} 篇文章`)
        selectedIds.value = [] // 清空选择
        getArticleList() // 刷新列表
      } else {
        ElMessage.error(response.msg || '批量发布失败')
      }
    } catch (error: any) {
      console.error('批量发布失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '批量发布失败，请重试')
    }
  }).catch(() => {
    // 用户取消发布
    console.log('用户取消批量发布')
  })
}

// 处理分页大小变更
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getArticleList()
}

// 处理当前页变更
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getArticleList()
}

// 获取状态类型
const getStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    0: 'success', // 已发布
    1: 'info', // 草稿
    2: 'warning', // 待审核
    5: 'warning', // 待发布
    10: 'info', // 草稿
    20: 'danger', // 已删除
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '已发布',
    1: '草稿',
    2: '待审核',
    5: '待发布',
    10: '草稿',
    20: '已删除',
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  getSites()

  // 从路由参数中获取筛选条件
  if (route.query.channelId) {
    searchForm.channelId = Number(route.query.channelId)
  }
  if (route.query.siteId) {
    searchForm.siteId = Number(route.query.siteId)
    getChannels(searchForm.siteId)
  }

  getArticleList()
})
</script>

<style scoped lang="scss">
.article-management {
  padding: 24px;
  background: #f8f9fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .header-left {
      .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #2c3e50;
        margin: 0 0 6px 0;
      }

      .page-desc {
        font-size: 14px;
        color: #6c757d;
        margin: 0;
      }
    }

    .header-right {
      .add-btn {
        height: 40px;
        padding: 0 20px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 6px;
      }
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .search-form {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 16px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .table-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid #f0f2f5;
      background: #fafbfc;

      .table-info {
        .total-count {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
        }
      }

      .table-actions {
        display: flex;
        gap: 8px;
      }
    }

    .table-wrapper {
      .el-table {
        .el-table__header-wrapper {
          .el-table__header {
            th {
              background: #f8f9fa !important;
              color: #606266 !important;
              font-weight: 600;
              border-bottom: 1px solid #ebeef5;
            }
          }
        }

        .el-table__body-wrapper {
          .el-table__body {
            tr {
              &:hover {
                background: #f5f7fa !important;
              }

              td {
                border-bottom: 1px solid #f0f2f5;
                padding: 16px 0;
              }
            }
          }
        }
      }

      .article-item {
        display: flex;
        align-items: flex-start;
        gap: 12px;

        .article-image-wrapper {
          flex-shrink: 0;

          .article-image {
            width: 60px;
            height: 45px;
            object-fit: cover;
            border-radius: 6px;
            border: 1px solid #e9ecef;
          }
        }

        .article-content {
          flex: 1;
          min-width: 0;

          .article-title {
            font-size: 15px;
            font-weight: 600;
            color: #2c3e50;
            cursor: pointer;
            margin-bottom: 4px;
            line-height: 1.4;

            &:hover {
              color: #409eff;
            }
          }

          .article-subtitle {
            font-size: 13px;
            color: #6c757d;
            margin-bottom: 6px;
            line-height: 1.3;
          }

          .article-meta {
            display: flex;
            gap: 12px;

            .meta-item {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }

      .date-text {
        font-size: 13px;
        color: #606266;
      }

      .action-buttons {
        display: flex;
        gap: 4px;
        justify-content: center;

        .el-button {
          font-size: 12px;
          padding: 4px 8px;
        }
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }
}
</style>